﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using UniRlv.COL;
using UniRlv.Utility;
using UniRlv.Utility.Extend;

namespace UniRlv.UI.Main.WarerHourseIn
{
    public partial class FrmStationStatus : Form
    {
        public int m_nRatio { get; set; }//父包装比值

        public int m_nTopRatio { get; set; }//顶级包装比值

        public int m_nStation { get; set; }
        public int m_nPackage { get; set; }
        public bool m_bTop { get; set; }

        string tmpDir, fileTmp, filePick;

        public bool bInit = false;

        public FrmStationStatus(int nStation, int nRatio, bool bTop)
        {
            InitializeComponent();

            m_nRatio = nRatio;
            m_nStation = nStation;
            m_bTop = bTop;

            FrmMain.GetInstance().CodeSaveEvent += CodeSaveEventHandler;
            FrmMain.GetInstance().CodePrintEvent += CodeSavePrintHandler;
        }


        private void FrmStationStatus_Load(object sender, EventArgs e)
        {
            SetScan();

            if (m_nStation == 2 && PublicObject.bSecond)
            {
                lbPickTip.Text = "二次扫描";
                SetScan2();
            }

            if (m_nStation == 1)
            {
                lbPick.Text = PublicObject.Picks1.ToString();
            }

            if (m_bTop)
            {
                lbPackTip.Text = "顶级码";
                lbPickTip.Text = "漏扫";
                lbUnpackTip.Text = "手扫";

                if (m_nStation>2)
                {
                    btnZero.Visible = true;
                }
                
            }
            else
            {
                lbPackTip.Text = string.Format("{0}级码（{1}个一包装）", m_nStation, m_nRatio);
            }

            if (m_nStation == 1)
            {
                //创建日志文件夹'
                tmpDir = Application.StartupPath + "\\logLevel1";
                if (!Directory.Exists(tmpDir))
                {
                    Directory.CreateDirectory(tmpDir);
                }

                fileTmp = string.Format("{0}\\{1}_{2}.log", tmpDir, m_nStation, PublicObject.CurTask.ID);

                if (File.Exists(fileTmp))
                {
                    txtMsg.Text = File.ReadAllText(fileTmp);
                }

                filePick = string.Format("{0}\\入库日期{3}_任务号{1}_批次号{2}.log", tmpDir, PublicObject.CurTask.ID, PublicObject.CurTask.batch, DateTime.Now.ToString("yyyyMMdd"));
            }
            else
            {
                //创建日志文件夹'
                tmpDir = Application.StartupPath + "\\log";
                if (!Directory.Exists(tmpDir))
                {
                    Directory.CreateDirectory(tmpDir);
                }

                fileTmp = string.Format("{0}\\{1}_{2}.log", tmpDir, m_nStation, PublicObject.CurTask.ID);

                if (File.Exists(fileTmp))
                {
                    txtMsg.Text = File.ReadAllText(fileTmp);
                }

                filePick = string.Format("{0}\\入库日期{3}_任务号{1}_批次号{2}.log", tmpDir, PublicObject.CurTask.ID, PublicObject.CurTask.batch, DateTime.Now.ToString("yyyyMMdd"));
            }

            if (ConfigurationHelper.HasSetting("font" + m_nStation))
            {
                txtMsg.Font = new Font("宋体", (float)ConfigurationHelper.AppGetDouble("font" + m_nStation));
            }
            else
            {
                ConfigurationHelper.AppSet("font" + m_nStation, ""+txtMsg.Font.Size);
            }
            bInit = true;
        }


        public void ClearLog()
        {
            File.Delete(fileTmp);
            txtMsg.Text = "";
        }

        public void ScanRefresh()
        {
            SetScan();

            if (m_nStation == 2 && PublicObject.bSecond)
            {
                SetScan2();
            }

        }

        public void SetScan()
        {
            int qty = 0;

            switch (m_nStation)
            {
                case 1:
                    qty = PublicObject.arrCode1.Count;break;
                case 2:
                    qty = PublicObject.arrCode2.Count; break;
                case 3:
                    qty = PublicObject.arrCode3.Count; break;
                case 4:
                    qty = PublicObject.arrCode4.Count; break;
                default:
                    break;
            }

            CallCtrlWithThreadSafety.SetText(lbTotal, qty.ToString(), this);

            SetRemain(qty);
        }

        public void SetScan2()
        {
            List<string> li;
            int qty = CodePrcUtility.GetScanTwiceQty();
            CallCtrlWithThreadSafety.SetText(lbPick, qty.ToString(), this);
        }

        public void SetRemain(int total)
        {
            int qtyParent = 0;

            if (!m_bTop)
            {
                switch (PublicObject.CurTask.tagLevel)
                {
                    case 1:
                        qtyParent = PublicObject.arrCode1.Count; break;
                    case 2:
                        qtyParent = m_nTopRatio * PublicObject.arrCode2.Count; break;
                    case 3:
                        if (m_nStation == 1)
                        {
                            int tmp = m_nRatio * PublicObject.arrCode2.Count;
                            qtyParent = m_nTopRatio * PublicObject.arrCode3.Count;
                            qtyParent = Math.Max(tmp, qtyParent);
                        }
                        else
                        {
                            qtyParent = m_nTopRatio * PublicObject.arrCode3.Count; 
                        }
                        break;
                    case 4:
                        if (m_nStation == 1)
                        {
                            int tmp = m_nRatio * PublicObject.arrCode2.Count;
                            qtyParent = m_nTopRatio * PublicObject.arrCode4.Count;
                            qtyParent = Math.Max(tmp, qtyParent);
                        }
                        else
                        {
                            qtyParent = m_nTopRatio * PublicObject.arrCode4.Count;
                        }
                        break;
                    default:
                        break;
                }

                CallCtrlWithThreadSafety.SetText(lbUnpack, (total - qtyParent).ToString(), this);
            }
            else
            {

                CallCtrlWithThreadSafety.SetText(lbPick, PublicObject.TopLoss.ToString(), this);
                CallCtrlWithThreadSafety.SetText(lbUnpack, PublicObject.TopMan.ToString(), this);

                if (PublicObject.TopLoss == PublicObject.TopMan)
                {
                    lbPick.ForeColor = Color.Orange;
                    lbUnpack.ForeColor = Color.Orange;
                    lbUnpack.BackColor = Color.Blue;
                    lbPick.BackColor = Color.Blue;
                }
                else
                {
                    lbPick.ForeColor = Color.Red;
                    lbUnpack.ForeColor = Color.Red;
                    lbUnpack.BackColor = Color.White;
                    lbPick.BackColor = Color.White;
                }
            }
        }

        void AddLog(string s)
        {
            string msg = string.Format("[{0}]{1}\r\n", DateTime.Now.ToString("HH:mm:ss.fff"), s);
            CallCtrlWithThreadSafety.AppendText(txtMsg, msg, this);

            AppendFileLog(msg);
        }

        void AppendFileLog(string s)
        {
            File.AppendAllText(fileTmp, s);
        }

        /// <summary>
        /// 剔除日志记录
        /// </summary>
        /// <param name="s"></param>
        void AppendPickFileLog(string s)
        {
            string msg = string.Format("[{0}]{1}\r\n", DateTime.Now.ToString("HH:mm:ss.fff"), s);
            File.AppendAllText(filePick, msg);
        }

        private void CodeSavePrintHandler(object sender, CodePrintEventArg e)
        {
            Action<CodePrintEventArg> act = new Action<CodePrintEventArg>((arg) =>
            {
                if (arg!=null)
                {
                    if (arg.pi.StationNum == m_nStation)
                    {
                        SetScan();
                        if (!string.IsNullOrEmpty(e.Tip))
                        {
                            AddLog(e.Tip);
                        }
                    }
                    if (arg.pi.StationNum == m_nStation + 1)
                    {
                        //待包装有变化
                        
                        int total = Convert.ToInt32(CallCtrlWithThreadSafety.GetText(lbTotal, this));
                        SetRemain(total);
                    }
                }
            });

            if (this.IsHandleCreated)
            {
                this.Invoke(act, e);
            }
        }

        public void CodeSaveEventHandler(object sender, CodeSaveEventArg e)
        {
            Action<CodeSaveEventArg> act = new Action<CodeSaveEventArg>((arg) =>
            {
                if (arg!=null)
                {
                    LineDevice dev = arg.dev;
                    en_code_prc sta = arg.prcState;

                    if (dev.stationNumber == m_nStation)
                    {
                        if (e.CodeQtyChanged)
                        {
                            if (dev.twiceScan == 1)
                            {
                                SetScan2();
                            }
                            else
                            {
                                SetScan();
                            }
                        }
                        else if (sta == en_code_prc.CP_PICK)
                        {
                            if (m_bTop)
                            {
                                int total = Convert.ToInt32(CallCtrlWithThreadSafety.GetText(lbTotal, this));
                                SetRemain(total);
                            }
                            else if(m_nStation == 1)
                            { 
                                CallCtrlWithThreadSafety.SetText(lbPick, PublicObject.Picks1.ToString(), this);
                                AppendPickFileLog(string.Format("一级码剔除，当前一级码数量{0}，前一个一级码{1}", PublicObject.arrCode1.Count,
                                    PublicObject.arrCode1.Count>0? PublicObject.arrCode1[PublicObject.arrCode1.Count-1].code:"无"));
                            }
                            else if(m_nStation == 2)
                            {
                                AppendPickFileLog(string.Format("二级码剔除，当前二级码数量{0}，前一个二级码{1}", PublicObject.arrCode2.Count,
                                    PublicObject.arrCode2.Count > 0 ? PublicObject.arrCode2[PublicObject.arrCode2.Count - 1].code : "无"));
                            }
                            else if (m_nStation == 3)
                            {
                                AppendPickFileLog(string.Format("三级码剔除，当前三级码数量{0}，前一个三级码{1}", PublicObject.arrCode3.Count,
                                    PublicObject.arrCode3.Count > 0 ? PublicObject.arrCode3[PublicObject.arrCode3.Count - 1].code : "无"));
                            }


                        }

                        if (!string.IsNullOrEmpty(e.Tip))
                        {
                            string[] tips = e.Tip.Split(new string[] { "。" }, StringSplitOptions.RemoveEmptyEntries);

                            
                            if (sta != en_code_prc.CP_PICK)
                            {//2020-02-05增加，剔除时不用提示信息
                                AddLog(tips[tips.Length - 1]);
                                string tip = "";
                                switch (m_nStation)
                                {
                                    case 1:
                                        tip = string.Format("一级码异常剔除，异常原因={2}，当前一级码数量{0}，前一个一级码{1}", PublicObject.arrCode1.Count,
                                    PublicObject.arrCode1.Count > 0 ? PublicObject.arrCode1[PublicObject.arrCode1.Count - 1].code : "无", tips[tips.Length - 1]);
                                        break;
                                    case 2:
                                        tip = string.Format("二级码异常剔除，异常原因={2}，当前二级码数量{0}，前一个二级码{1}", PublicObject.arrCode2.Count,
                                    PublicObject.arrCode2.Count > 0 ? PublicObject.arrCode2[PublicObject.arrCode2.Count - 1].code : "无", tips[tips.Length - 1]);
                                        break;
                                    case 3:
                                        tip = string.Format("三级码异常剔除，异常原因={2}，当前三级码数量{0}，前一个三级码{1}", PublicObject.arrCode3.Count,
                                    PublicObject.arrCode3.Count > 0 ? PublicObject.arrCode3[PublicObject.arrCode3.Count - 1].code : "无", tips[tips.Length - 1]);
                                        break;
                                    case 4:
                                        tip = string.Format("四级码异常剔除，异常原因={2}，当前四级码数量{0}，前一个四级码{1}", PublicObject.arrCode4.Count,
                                    PublicObject.arrCode4.Count > 0 ? PublicObject.arrCode4[PublicObject.arrCode4.Count - 1].code : "无", tips[tips.Length - 1]);

                                        break;
                                    default:
                                        break;
                                }
                               
                                AppendPickFileLog(tip);
                            }

                            switch (m_nStation)
                            {
                                case 1:
                                    CallCtrlWithThreadSafety.SetText(lbPick, PublicObject.Picks1.ToString(), this);
                                    break;
                                case 2:
                                    if (PublicObject.bSecond)
                                    {
                                        SetScan2();
                                    }
                                    else
                                    {
                                        CallCtrlWithThreadSafety.SetText(lbPick, PublicObject.Picks2.ToString(), this);
                                    }
                                    break;
                                case 3:
                                    CallCtrlWithThreadSafety.SetText(lbPick, PublicObject.Picks3.ToString(), this);//刷新剔除数量
                                    break;
                                default:
                                    break;
                            }
                            
                        }
                    }
                    else if (dev.stationNumber > m_nStation)
                    {
                        if (e.CodeQtyChanged)
                        {//待包装有变化
                            int total = Convert.ToInt32(CallCtrlWithThreadSafety.GetText(lbTotal, this));
                            SetRemain(total);
                        }
                        else
                        {
                            if (sta != en_code_prc.CP_PRC_NORMAL || sta != en_code_prc.CP_NORMAL)
                            {//父工位剔除，可能影响本工位数量
                                ScanRefresh();
                            }
                        }

                        
                    }
                    else
                    {
                        if (sta == en_code_prc.CP_PRC_NORMAL)
                        {//手持操作，统一刷新
                            ScanRefresh();
                        }
                    }
                }
                else
                {
                    SetScan();

                    if (m_nStation == 1)
                    {
                        CallCtrlWithThreadSafety.SetText(lbPick, PublicObject.Picks1.ToString(), this);
                    }
                    else if (m_nStation == 2)
                    {
                        if (PublicObject.bSecond)
                        {
                            SetScan2();
                        }
                        else
                        {
                            CallCtrlWithThreadSafety.SetText(lbPick, PublicObject.Picks2.ToString(), this);
                        }
                        
                    }

                    if (!m_bTop)
                    {
                        int total = Convert.ToInt32(CallCtrlWithThreadSafety.GetText(lbTotal, this));
                        SetRemain(total);
                    }
                        
                }

            });

            if (this!=null && this.IsHandleCreated)
            {
                try
                {
                    this.Invoke(act, e);
                }
                catch (Exception)
                {

                }
                
            }
            
        }

        private void txtMsg_DoubleClick(object sender, EventArgs e)
        {
            txtMsg.Text = "";
            File.Delete(fileTmp);

        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtMsg.Text = "";
            File.Delete(fileTmp);
        }

        private void FrmStationStatus_FormClosing(object sender, FormClosingEventArgs e)
        {
            bInit = false;
            FrmMain.GetInstance().CodeSaveEvent -= CodeSaveEventHandler;
            FrmMain.GetInstance().CodePrintEvent -= CodeSavePrintHandler;
        }

        private void btnFont_Click(object sender, EventArgs e)
        {
            FontDialog font = new FontDialog();
            font.Font = txtMsg.Font;
            DialogResult dr = font.ShowDialog();
            if (dr == DialogResult.OK)
            {
                txtMsg.Font = font.Font;
                ConfigurationHelper.AppSet("font" + m_nStation, "" + txtMsg.Font.Size);
            }
        }

        private void FrmStationStatus_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        private void btnZero_Click(object sender, EventArgs e)
        {
            //先判断是否需要打印
            string msg = string.Empty;

            if (PublicObject.bPrint)
            {
                msg = "该操作将自动打印零箱码并移除最后不满整包装的二级包装数据（含子数据），确认继续？";
            }
            else
            {
                msg = "该操作将自动移除最后不满整包装的二级包装数据（含子数据），确认继续？";
            }

            DialogResult dr =  MessageBox.Show(msg, "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

            if (dr == DialogResult.OK)
            {
                msg = string.Empty;

                if (PublicObject.bPrint)
                {
                    if (!WorkSpace.GetInstance().PrintZeroLabel(ref msg))
                    {
                        AddLog("打印零箱标签失败：" + msg);
                        MessageBox.Show("打印零箱标签失败：" + msg);
                        return;
                    }
                }

                if (CodePrcUtility.ZeroRemain(ref msg))
                {
                    WorkSpace.GetInstance().RefreshCodeQty();
                    AddLog("零箱成功！");
                    MessageBox.Show("操作成功！");
                }
                else
                {
                    AddLog("零箱操作失败：" + msg);
                    MessageBox.Show("零箱操作失败：" + msg);
                }

            }

        }
    }
}
